#include "client.h"

Client::Client(unsigned int clientId,string serverIpAddress,string serverPort,unsigned int clientBandwidth,unsigned int fileId){
	_serverIpAddress = serverIpAddress;
	_serverPort = serverPort;
	_clientBandwidth = clientBandwidth;
	_fileId = fileId;
	_clientId = clientId;
}

Client::~Client(){
}

void
Client::startRequest(){
	cout<<"client "<<_clientId<<" start connect..."<<endl;
	int connfd = tcp_connect(_serverIpAddress.c_str(),_serverPort.c_str());
	ClientRequestPack requestPack;
	requestPack.messageType = htonl(REQUESTRESOURCE);
	requestPack.rsId = htonl(0);
	requestPack.fileId = htonl(_fileId);
	requestPack.clientId = htonl(_clientId);
	requestPack.clientBandwidth = htonl(_clientBandwidth);
	cout<<"the client "<<_clientId << " starting send the request to lb "<<endl;	
	writen(connfd,(void *)&requestPack,sizeof(ClientRequestPack));
	unsigned int rsId ;
	readn(connfd,(void *)&rsId,sizeof(unsigned int));
	requestPack.rsId = rsId;
	requestPack.messageType = htonl(REQUESTRS);
	//cout<<"messageType = "<<requestPack.messageType<<endl;
	cout<<"the client "<<_clientId << " starting request the resource from resource server "<<ntohl(rsId)<<endl;
	writen(connfd,(void *)&requestPack,sizeof(ClientRequestPack));
	if(0 == readn(connfd,(void*)&requestPack,sizeof(clientRequestPack))){
		perror("read error");
		exit(1);
	}
	if(ntohl(requestPack.messageType) == REQUESTRESOURCEOVER){
		cout<<"client "<< _clientId <<" request resource over" <<endl;
		pthread_exit(NULL);
	}else
		exit(1);
	
}
